package cc.ppay.sso.core.store;

import cc.ppay.sso.common.constant.SsoConstant;
import cc.ppay.sso.common.model.SsoUser;
import cc.ppay.sso.core.config.SsoRedisProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * local login store
 *
 * @author xuxueli 2018-04-02 20:03:11
 */
@Component
public class SsoLoginStore {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private SsoRedisProperties ssoRedisProperties;

    /**
     * get
     *
     * @param storeKey
     * @return
     * @author Ade.Xiao 2021/1/29 18:04
     */
    public SsoUser get(String storeKey) {

        String redisKey = redisKey(storeKey);
        Object objectValue = redisTemplate.opsForValue().get(redisKey);
        if (objectValue != null) {
            SsoUser ssoUser = (SsoUser) objectValue;
            return ssoUser;
        }
        return null;
    }

    /**
     * remove
     *
     * @param storeKey
     * @author Ade.Xiao 2021/1/29 18:04
     */
    public void remove(String storeKey) {
        String redisKey = redisKey(storeKey);
        redisTemplate.delete(redisKey);
    }

    /**
     * put
     *
     * @param storeKey
     * @param ssoUser
     * @author Ade.Xiao 2021/1/29 18:04
     */
    public void put(String storeKey, SsoUser ssoUser) {
        String redisKey = redisKey(storeKey);
        redisTemplate.opsForValue().set(redisKey, ssoUser, ssoRedisProperties.getRedisExpireMinute() * 60, TimeUnit.SECONDS);
    }

    /**
     * 构建redis缓存key
     *
     * @param sessionId
     * @return
     * @author Ade.Xiao 2021/1/29 18:04
     */
    private String redisKey(String sessionId) {
        return SsoConstant.SSO_SESSIONID.concat("#").concat(sessionId);
    }

    /**
     * 获取缓存时效时间
     *
     * @author Ade.Xiao 2021/1/29 18:04
     */
    public int getRedisExpireMinute() {
        return ssoRedisProperties.getRedisExpireMinute();
    }
}
